package main

import (
	"fmt"
	"log"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type ErrorStruct struct {
	Id              uint   `json:"id" gorm:"primaryKey;autoIncrement"`
	Name            string `json:"name" gorm:"type:varchar(32)"`
	Info            string `json:"info" gorm:"type:varchar(32)"`
	TriggerDate     string `json:"trigger_date" gorm:"type:varchar(32)"`
	TriggerTime     string `json:"trigger_time" gorm:"type:varchar(32)"`
	TriggerDateTime string `json:"trigger_date_time" gorm:"type:varchar(32)"`
	ResolveDate     string `json:"resolve_date" gorm:"type:varchar(32)"`
	ResolveTime     string `json:"resolve_time" gorm:"type:varchar(32)"`
	ResolveDateTime string `json:"resolve_date_time" gorm:"type:varchar(32)"`
	ErrorCode       string `json:"error_code" gorm:"type:varchar(32)"`
}

var myDB *gorm.DB

func initDB() {
	// 连接 SQLite 数据库，如果数据库文件不存在则创建
	var err error
	myDB, err = gorm.Open(sqlite.Open("ztmodbus.db"), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect to database: %v", err)
	}
	// 自动迁移模式（自动创建或更新数据库表结构）
	err = myDB.AutoMigrate(&ErrorStruct{})
	if err != nil {
		log.Fatalf("failed to migrate database: %v", err)
	}

	// 定时清除db数据
	dbTicker := time.NewTicker(10 * time.Second)
	go func() {
		fmt.Println("Starting database cleaner...")
		for range dbTicker.C {
			fmt.Println("Clearing old data from ErrorStruct table...")
			// 清除ErrorStruct表1分钟以前的数据，使用trigger_date_time字段判断
			myDB.Where("trigger_date_time < ?", time.Now().Add(-1*time.Minute)).Delete(&ErrorStruct{})
		}
	}()
}

func updateError(singlePt PtStruct) {
	var errors []ErrorStruct
	myDB.Where("name = ? AND resolve_time = ?", singlePt.Name, "").Find(&errors)
	if singlePt.Value == byte(1) && len(errors) == 0 {
		var newError = ErrorStruct{
			Info: singlePt.Remark,
			Name: singlePt.Name,
			// Type:        singlePt.Belong,
			TriggerDate:     time.Now().Format("2006-01-02"),
			TriggerTime:     time.Now().Format("15:04:05"),
			TriggerDateTime: time.Now().Format("2006-01-02 15:04:05"),
			ErrorCode:       singlePt.ErrorCode,
		}
		myDB.Create(&newError)
	}
	if singlePt.Value == byte(0) && len(errors) > 0 {
		var result = errors[0]
		result.ResolveDate = time.Now().Format("2006-01-02")
		result.ResolveTime = time.Now().Format("15:04:05")
		result.ResolveDateTime = time.Now().Format("2006-01-02 15:04:05")
		myDB.Model(&ErrorStruct{}).Where("id = ?", result.Id).Updates(result)
	}
}
